<template>
  <!-- // 分配角色 -->
  <div>
    <!-- 假装这里有所有的权限 -->
    <el-tree
      ref="treeRef"
      node-key="id"
      :data="list"
      :props="{label:'name'}"
      show-checkbox
      default-expand-all
      check-strictly
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permiissions'
import { getRoleDetail, assignPermission } from '@/api/settings'
import { tranListToTreeData } from '@/utils'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      permIds: []

    }
  },
  created() { this.loadPermissionList() },
  methods: {
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('getPermissionList', res.data)
        // 保存数据
        this.list = tranListToTreeData(res.data)
        // this.list = res.data
        // console.log(this.list, '树形结构')
        this.loadRoleDetail()
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 获取具体权限信息
    async loadRoleDetail() {
      try {
        console.log(this.roleId, 'this.roleId')
        const res = await getRoleDetail(this.roleId)
        console.log('getPermissionDetail', res)
        // 保存数据
        this.permIds = res.data.permIds
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)// 自动选中已分配节点
      } catch (err) {
        console.log('getPermissionDetail', err)
      }
    },
    // 更新分配权限

    async updatePermission() {
      // 获取已选中的权限
      console.log(this.$refs.treeRef.getCheckedKeys(), 'this.$refs.treeRef.getCheckedKeys()')
      this.permIds = this.$refs.treeRef.getCheckedKeys()
      try {
        const res = await assignPermission({ id: this.roleId, permIds: this.permIds })
        console.log('updatePermission', res)
        // 保存数据
      } catch (err) {
        console.log('updatePermission', err)
      }
    },
    hSubmit() {
      this.$emit('close')
      this.updatePermission()
    },
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

